// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import Vuex from 'vuex'
import store from './store/index.js'
import router from './router'
import './config/rem'
import FastClick from 'fastclick' // 引入FastClick
import { Popup, Toast, Lazyload } from 'vant';
import axios from 'axios';
import VueAxios from 'vue-axios'
import VueRouter from 'vue-router';

Vue.use(VueRouter);
Vue.use(Popup).use(Toast)

// 使用 fastclick
FastClick.attach(document.body); 
// 提示框
Vue.prototype.$Tip = msg => Toast({
  message: msg,
  forbidClick: true,
  duration: 1500
});
// 加载提示
Vue.prototype.$Loading = msg => Toast.loading({
  message: msg,
  forbidClick: true,
  duration: 0
});

Vue.use(VueAxios, axios, Vuex)
.use(Lazyload, {
  preLoad: 1.3,
  error: require('@/assets/loading-error.png'),
  loading: require('@/assets/loading-img.gif'),
  attempt: 1
})

Vue.config.productionTip = false;


// 解析url参数并获取code
function getUrlParam(name) {   //name为要获取的参数名  
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");  
  var rrr = decodeURIComponent(window.location.search);  
  var r = rrr.substr(1).match(reg);  
  if(r != null) return unescape(r[2]);  
  return null;  
}

// sessionStorage.setItem('user', JSON.stringify({
//   uid: '24bbnUPIDkVK|jia|O7zKMBs|jia|CS6CmEAmCjDDdPZfivF'
// }));


// 请求微信服务器获取code
function getUserCode() {
  // 请求微信服务器获取code参数
  let redirectURL = encodeURI(window.location.href.split('#')[0]);
  const appid = 'wxa99df6fd7e44916c'; 
  const scope = 'snsapi_userinfo';
  const base = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=';
  let state;
  let surl;
  let reserveUrl;
  if (window.location.href.indexOf('type') !== -1) {
    // 用户分享进入网站
    state = window.location.href.split('type=')[1].split('&')[0];
    surl = window.location.href.split('surl')[1];
    if(window.location.href.indexOf('&from') !== -1) {
      surl = window.location.href.split('surl')[1].split('&from')[0];
    }
    window.location.href =base + appid +'&redirect_uri='+ redirectURL +'&response_type=code&scope='+ scope +'&state=' + state +'*surl' + surl+ '#wechat_redirect';
  } else if(window.location.href.indexOf('reserve') !== -1){
    //用户从公众号预约进入
    reserveUrl = window.location.href.split('reserve=')[1];
    window.location.href =base + appid +'&redirect_uri='+ redirectURL +'&response_type=code&scope='+ scope +'&state=' + reserveUrl + '#wechat_redirect';
  } else {
    window.location.href =base + appid +'&redirect_uri='+ redirectURL +'&response_type=code&scope='+ scope + '#wechat_redirect';
  }
};

// 路由变化时
router.beforeEach((to, from, next) => {
  // 读取sessionStorage的user
  let user = JSON.parse(sessionStorage.getItem('user'));
  

  // 已登录 
  if (user) { 
    // 赋值vuex
    store.commit('updateUser', user);
    next();
  }

  // 未登录
  if (!user) {
    // 检测url是否有code参数
    const code = getUrlParam('code');

    // 还未完成微信授权
    if (!code) {
      // 获取code
      getUserCode();
    }

    // 已完成微信授权
    if (code) {
        Toast({
          type: "loading",
          message: "登录中",
          forbidClick: true,
          duration: true
        });
          
        // 登录
        axios.get('http://jxjq.0791jr.com/index.php?m=App&c=Mine&a=wx_login', {
          params: {
            code: code
          }
        }).then(res => {
          if (res.status == 200) {
            Toast.clear();
            const data = res.data.data;       
            const info = data.user_info;
            if (info.status == 0) { Toast({ message: '您的账号已禁用' }); return }
            let userInfo = {
              uid: info.id, // 用户id(密文)
              user_id: info.user_id,// 用户id(明文)
              // identity: info.type - 1, // 用户身份， 0普通用户， 1分销商
              avatar: info.avatar, // 头像
              nickname: info.nickname, // 昵称
              sex: info.sex == 1 ? '男' : '女',
              birthday: info.birthday,
              mobile: info.mobile,//用户手机号
              issetpass: data.is_set_pay_pwd, // 是否设置了支付密码， 0未设置， 1设置了
            }
            // 存sessionStorage/更新vuex
            sessionStorage.setItem('user', JSON.stringify(userInfo)); 
            store.commit('updateUser', userInfo);
            // Toast({ message: "登录成功", duration: 1000, forbidClick: true });
            
            
            const reserveUrl = window.location.href.split('&state=')[1].split('#')[0];
            if (reserveUrl.indexOf('*') !== -1) {
              if (reserveUrl.indexOf('*surl') !== -1) {
                // 如果是要进入分销页面
                const spid = window.location.href.split('&state=')[1].split('#')[0];
                const surl = window.location.href.split('*surl')[1].split('#')[0].replace(/\*/g,'/');
                const pid = spid.split('*surl')[0];
                if (pid=='undefined'||pid==''||pid==null) {
                  Toast({
                    message: '网络错误，请重新扫码'
                  });
                  return;
                } else {
                  next({path: surl+'?spid=' + spid.split('*surl')[0]});
                }
              } else {
                // 如果从公众号进入
                next({path: reserveUrl.replace(/\*/g,'/')});
              }
            } else {
              next();
            }
            
          } else {
            Toast({
              message: '账号异常'
            });
            return
          }
        }).catch(err => {
            Toast({
              message: '登录失败，请刷新重试'
            })
        }) 

    }
  }
})
/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  template: '<App/>'
})
